package com.ittx.dzt.weidian.service;

import cn.hutool.core.collection.CollectionUtil;
import com.ittx.dzt.edi.constant.GeneralConstant;
import com.ittx.dzt.edi.dto.PlatformApiParamDTO;
import com.ittx.dzt.edi.dto.StoreConfigDTO;
import com.ittx.dzt.edi.dto.TimeFrameDTO;
import com.ittx.dzt.sys.response.Result;
import com.ittx.dzt.weidian.constant.WeidianApiConstant;
import com.ittx.dzt.weidian.handler.AbstractWeidianByTimeApiHandler;
import lombok.extern.slf4j.Slf4j;
import open.constant.PlatformApiConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 商品信息增量下载【下载所有状态商品】
 * <p>
 * cy.sku.download.byTimeFrame
 * 获取店铺商品列表(vdian.item.list.get) https://open.weidian.com/#/api/178
 * </p>
 *
 * @author wl_code@163.com
 * @version 1.0
 * @date 2025/4/1
 */
@Slf4j
@Service
public class WeidianSkuDownloadByTimeFrameService extends AbstractWeidianByTimeApiHandler<TimeFrameDTO> {

	private static final int DEFAULT_PAGE_SIZE = 50;
	@Autowired
	private WeidianSkuDownloadBySpuIdService weidianSkuDownloadBySpuIdService;


	@Override
	protected String getMqTopic() {
		return WeidianApiConstant.Rocket.WEIDIAN_PRODUCT_LIST_BY_TIME_BATCH_SPLIT_TOPIC;
	}


	@Override
	public String getLocalApiMethod() {
		return open.constant.PlatformApiConstant.InboundInterface.SKU_DOWNLOAD_BY_TIMEFRAME;
	}

	@Override
	protected Result<?> doProcessByNormalType(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO) {
		// 分发数据,异步下载
		Map<String, Boolean> logMap = new HashMap<>();
		// 判断是rds还是sdk
		StoreConfigDTO storeConfig = platformApiParamDTO.getStoreConfig();
		return this.requestListBySdk(platformApiParamDTO, timeFrameDTO, logMap);

	}

	@Override
	protected Result<?> doProcessByCheckType(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO) {
		//探查成功时不返回完整数据,只返回数量
		StoreConfigDTO storeConfig = platformApiParamDTO.getStoreConfig();
		return this.requestListBySdk(platformApiParamDTO, timeFrameDTO, null);
	}

	@Override
	protected Result<?> doProcessByIdType(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO) {
		String productId = platformApiParamDTO.getPlatformIdentifierTag();
		return this.asyncHandlerById(platformApiParamDTO, productId);
	}

	/**
	 * 请求平台接口
	 */
	private Result<?> requestListBySdk(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO, Map<String, Boolean> logMap) {
		Map<String, Object> params = new HashMap<>();
		// 开始时间
		params.put("update_start", timeFrameDTO.getFrom().format(DateTimeFormatter.ofPattern(GeneralConstant.DEFAULT_DATE_TIME_PATTERN)));
		// 结束时间
		params.put("update_end", timeFrameDTO.getTo().format(DateTimeFormatter.ofPattern(GeneralConstant.DEFAULT_DATE_TIME_PATTERN)));

		params.put("page_size", DEFAULT_PAGE_SIZE);
		long page = 1;
		// 第一次查询，获取总页数 第一页为1
		params.put("page_num", page);
		Result<?> result = this.executeWeidianApi(platformApiParamDTO.getStoreConfig(), params, platformApiParamDTO.getRequestId());
		if (result.hasError()) {
			return result;
		}
		Map<String, Object> resultMap = (Map<String, Object>) result.getData();
		Map<String, Object> dataMap = (Map<String, Object>) resultMap.get("result");
		// 商品总数
		int total = Integer.parseInt(dataMap.get("item_num").toString());
		// 探查模式只返回商品总数
		if (PlatformApiConstant.ApiByTime.CHECK.equals(platformApiParamDTO.getQueryType())) {
			return Result.success().addData(total);
		}
		// 总页数
		Integer totalPage = this.totalPage(total, DEFAULT_PAGE_SIZE);
		if (totalPage > 0) {
			// 倒序查询，防止数据遗漏
			for (int i = totalPage; i > 0; i--) {
				params.put("page", i);
				result = this.executeWeidianApi(platformApiParamDTO.getStoreConfig(), params, platformApiParamDTO.getRequestId());
				if (result.hasError()) {
					return result;
				}
				resultMap = (Map<String, Object>) result.getData();
				dataMap = (Map<String, Object>) resultMap.get("result");
				List<Map<String, Object>> items = (List<Map<String, Object>>) dataMap.get("items");
				if (CollectionUtil.isNotEmpty(items)) {
					// 分发数据到MQ，异步消费下载
					for (Map<String, Object> item : items) {
						String productId = item.get("itemid") + "";
						sendToSplitTopic(platformApiParamDTO, productId, logMap);
					}
				}
			}
		}
		return Result.success(logMap);
	}

	/**
	 * 多线程处理逻辑
	 */
	@Override
	public Result<?> asyncHandlerById(PlatformApiParamDTO platformApiParamDTO, String productId) {
		Result<?> result = weidianSkuDownloadBySpuIdService.getProductById(productId, platformApiParamDTO);
		if (result.hasError()) {
			return result;
		}
		return this.sendRequestToPlatform(platformApiParamDTO, result.getData(), true);
	}

	@Override
	public String getWeidianMethod() {
		return "vdian.item.list.get";
	}

	@Override
	public String getWeidianApiVersion() {
		return "1.1";
	}

	@Override
	public String getWeidianApiFormat() {
		return null;
	}
}
